<?php

/**
 * pages actions.
 *
 * @package    dolpheuscms
 * @subpackage pages
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class pagesComponents extends sfComponents
{

    /**
     * Function that builds the menu in the footer
     * @param sfWebRequest $request 
     */
    public function executeFooter(sfWebRequest $request)
    {
        $treeObject = Doctrine::getTable('Pages')->getTree();
        $tree = $treeObject->fetchTree();

        $this->buildFooterMenu($tree);
        return sfView::NONE;
    }

    /**
     * Function that builds the <ul> HTML representation for a node
     * @param sfWebRequest $request
     */
    public function executeMenu(sfWebRequest $request)
    {
        $treeObject = Doctrine::getTable('Pages')->getTree();
        $tree = $treeObject->fetchTree();
        
        $this->buildMenu($tree, $request);
        return sfView::NONE;
    }

    /**
     * Function that builds the <ul> HTML representaiton
     * @param Doctrine_Collection $tree
     * @param sfWebRequest $request
     */
    private function buildMenu(Doctrine_Collection $tree, sfWebRequest $request)
    {
        // Here we store the UL-list
        $output = '';
        // Iterating tree from a root
        foreach ($tree as $node) {
            if ($node->getLevel() == 1) {
                // Priting item without closing tag
                $output .= $this->getLi($node, $request);
            }
        }
        echo '<ul id="navigation">';
        echo $output;
        echo '</ul>';
    }

    /**
     * Function builds <li> HTML representation for a given node
     * Closing tag (/li) is not included
     * @param array $node
     */
    private function getLi($node, $request)
    {
        $splittedUrl = explode("/", $request->getParameter('url'));

        if ( $node['url'] == $request->getParameter('url') ) {
            return '<li><a class="active" href="/' . $node['url'] . '">' . $node['title'] . '</a></li>';
        } else {
            return '<li><a href="/' . $node['url'] . '">' . $node['title'] . '</a></li>';
        }
    }

    /**
     * Function that builds the footer menu
     * @param Doctrine_Collection $tree
     */
    private function buildFooterMenu(Doctrine_Collection $tree)
    {
        $output = '';
        // counter
        $i = 0;
        foreach ($tree as $node) {
            if ($node['level'] == 1) {
                if ($i < count($tree) - 1) {
                    $output .= '<a href="/' . $node['url'] . '">' . $node['title'] . '</a> | ';
                } else {
                    $output .= '<a href="/' . $node['url'] . '">' . $node['title'] . '</a>';
                }
            }
            $i++;
        }
        echo $output;
    }

}